<template>
  <div class="game_home">
    <client-box :is-un-show="isUnShowClientHeader" title="商城首页">
      <template v-slot:content>
        <!-- router-view -->
        <div class="main_router_view">
          <router-view />
        </div>
      </template>
    </client-box>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { getToken } from '@/lib/auth';
import { judgeToLogout, loginOidc } from '@/lib/oidc_fun';
import { api_GET_UsersOrganizationUnit } from '@/extend/api/swaggerApi/identity';
import { api_GET_EventsManagementRegisterId } from '@/extend/api/gameswaggerApi/app';
import clientBox from '@/layout/client/index';
export default {
  components: {
    clientBox
  },
  data() {
    return {
      gameId: '',
      showSysManagementPage: false
    };
  },
  computed: {
    ...mapState({
      archival: state => state.app.archival,
      archivalUrl: state => state.app.archivalUrl,
      copyright: state => state.app.copyright,
      copyrightUrl: state => state.app.copyrightUrl,
      currentUserType: state => state.user.currentUserType,
      currentUserIndInfo: state => state.user.currentUserIndInfo,
      info: state => state.user.info,
      tokenInfo: state => state.user.token || getToken()
    }),
    blankPagePre() {
      return window.location.origin + '/game.html#/';
    },
    sysManagementPage() {
      return window.location.origin;
    },
    tenantId() {
      let tenantId = this.gameId
        ? this.gameId.lastIndexOf('_') > -1 && this.gameId.split('_')[1] !== 'plat'
          ? this.gameId.split('_')[1]
          : ''
        : '';
      tenantId = tenantId || this.$route.query.tenantid;
      return tenantId;
    },
    // 是否不显示c端头部底部
    isUnShowClientHeader() {
      const _ids = this.$route.params.id;
      if (_ids && _ids.split('_').length > 0 && _ids.split('_')[_ids.split('_').length - 1] === 'plat') {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler() {
        this.gameId = this.$route.params.id;
      }
    },
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.handleShowBtnWithSys();
        this.getIndividualInfo();
      }
    }
  },
  created() {
    this.showSysManagementPage = false;
    if (this.currentUserType) {
      this.handleShowBtnWithSys();
      this.getIndividualInfo();
    }
  },
  methods: {
    jumpToUrl (url) {
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = url;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 处理显示后台跳转按钮显示
    async handleShowBtnWithSys() {
      this.showSysManagementPage = false;
      if (this.currentUserType && 'delegationId' in this.currentUserType) {
        const _delegationId = this.currentUserType.delegationId;
        if (_delegationId && this.getManageSysIdentity()) {
          this.showSysManagementPage = true;
        }
      }
    },
    getManageSysIdentity() {
      // const identityList = [
      //   'AbpIdentity',
      //   'EventsManagement.Competitions',
      //   'Order',
      //   'GameManage',
      //   'Logistics.Default',
      //   'Train.Trainnings',
      //   'Mall.Store',
      //   'Club.Management'
      // ];
      // const _info = this.info;
      // for (const i in identityList) {
      //   if (_info.permissions.includes(identityList[i])) {
      //     return true;
      //   }
      // }
      const _info = this.info;

      // 如果用户被禁用，则有权限但无法进入后台及道馆，屏蔽掉入口
      if (_info.currentOrganizationUnit === null && _info.currentOrganizationUnitId === null) {
        return false;
      }

      if (_info.permissions && _info.permissions.length > 0) {
        return true;
      }
      return false;
    },
    // 头像回显
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    getCurrentOrg() {
      return new Promise((resolve, reject) => {
        api_GET_UsersOrganizationUnit().then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    goGameInfo() {
      if (this.gameId) {
        this.$router.push({
          path: `/home/${this.gameId}`
        });
      }
    },
    goLogin() {
      let tenantId = this.tenantId ? this.tenantId : '';
      tenantId = tenantId + '___' + ENVIR;
      let href = window.location.href;
      href =
        href.indexOf('#') > -1
          ? href.indexOf('?') > -1
            ? href + '&'
            : href + '?'
          : href + '#/?';
      href = href
        .replace(/loginRandom=[0-9]+|loginRandom=/g, '')
        .replace(/&&+/g, '&')
        .replace('?&', '?');
      href = href + 'loginRandom=' + new Date().getTime();
      // 跳转登录
      loginOidc({
        state: window.btoa(href),
        acr_values: tenantId ? window.btoa(tenantId) : ''
      });
    },
    logoutConfirm() {
      this.$confirm('您确定退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout();
      });
    },
    async logout() {
      const tenantId = !(
        this.$route.params &&
        this.$route.params.id &&
        this.$route.params.id.lastIndexOf('_') > -1
      )
        ? this.$store.state.user.info && this.$store.state.user.info.tenantId
          ? this.$store.state.user.info.tenantId
          : ''
        : this.tenantId || '';
      await this.$store.dispatch('user/logout');
      // this.goLogin();
      let refs =
        window.location.href.indexOf('/myCenter') > -1
          ? window.location.origin + window.location.pathname + '#/myCenter'
          : window.location.href;
      refs =
        refs.indexOf('#') > -1
          ? refs.indexOf('?') > -1
            ? refs + '&'
            : refs + '?'
          : refs + '#/?';
      refs = refs
        .replace(/tenantid=[0-9a-z\-]+|tenantid=/g, '')
        .replace(/&&+/g, '&')
        .replace('?&', '?');
      judgeToLogout(refs + 'tenantid=' + tenantId);
      // this.tokenInfo = getToken();
    },
    toMyCenter() {
      window.open(this.blankPagePre + 'myCenter', '_blank');
    },
    toSysManagementPage() {
      window.open(this.sysManagementPage, '_blank');
    },
    getIndividualInfo() {
      return new Promise((resolve, reject) => {
        if (!this.currentUserType.registerId) return;
        this.personInfoLoading = true;
        api_GET_EventsManagementRegisterId(
          this.currentUserType.registerId,
          { IncludeGender: true, IncludeIdCardType: true }
        ).then(res => {
          this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
          reject(error);
        });
      });
    }
  }
};
</script>

<style scoped>
.game_header_title{
  padding-left: 40px;
}
.game_header_login{
  padding-right: 40px;
}
.game_header {
  width: 100%;
  min-width: 1200px;
  height: 60px;
  background-color: #31456c;
}
.game_footer {
  width: 100%;
  min-width: 1200px;
  background-color: #31456c;
}
.game_header_content,
.game_footer_content {
  width: 1200px;
  margin: 0 auto;
  color: #fff;
}
.game_header_content {
  line-height: 60px;
  font-size: 16px;
}
.game_footer_content {
  font-size: 15px;
}
.game_footer_logo {
  height: 64px;
  vertical-align: middle;
  margin-right: 35px;
}
.game_footer_link {
  text-align: center;
}
.game_footer_linkItem {
  margin-right: 40px;
  cursor: pointer;
}
.game_footer_linkImg {
  width: 38px;
  height: 38px;
  margin-bottom: 20px;
}
.game_header_login,
.game_info_title {
  cursor: pointer;
}
.main_router_view {
  box-sizing: border-box;
  margin-bottom: 30px;
  min-height: calc(100vh - 60px - 262px);
}
.archival_copyright {
  height: 60px;
  padding-top: 10px;
  line-height: 20px;
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.archival_copyright a {
  transition: all 0.3s ease;
}
.archival_copyright a:hover {
  text-decoration: underline;
}
.copyright img {
  vertical-align: middle;
  margin-right: 2px;
  width: 18px;
}
.footer_nav_item:hover {
  cursor: pointer;
  text-decoration: underline;
}
.game_header  .username {
  color: #fff;
  margin-left: 10px;
  line-height: initial;
}
.game_header .person_img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  vertical-align: middle;
}
.el-dropdown-menu__item {
  min-width: 110px;
}
</style>
